package liming.ai.code.java_maven.chat;

import liming.ai.client.impl.deepseek.DeepSeekClient;
import liming.ai.code.java_maven.info.ProjectInfo;
import liming.ai.data.deepseek.ChatCompletionRequest;
import liming.ai.data.deepseek.Message;
import liming.tool.file.FileRW;
import liming.tool.lock.CodeLock;
import liming.tool.lock.LockAtomicLong;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;

/**
 * 用于调用ai进行问答
 */
public class QueryAi {
    DeepSeekClient deepSeekClient;
    ProjectInfo projectInfo;

    public QueryAi(File configFile) throws Exception {
        FileRW.setDefaultWritingEncoding(FileRW.FileEncoding.UTF8);
//        this.deepSeekClient = new DeepSeekClient(configFile);
        projectInfo = ProjectInfo.getInstance(configFile);
        FileRW.writeTextFile(new File("./projectConfig.json"),projectInfo.toJson().toString(),false);
//        initContext();
    }

    public String chat(String query) {
        return deepSeekClient.chat(false, query);
    }

    public String chat(String query, ChatCompletionRequest request) {
        String chat = deepSeekClient.chat(query, request);
        System.out.println(chat);
        return chat;
    }

    //初步理解当前环境
    private void initContext() {
        JSONObject query = getRequestJson("query", "请根据当前环境、项目结构和内容，生成缺少的部分,如果不缺少，则返回type为code的，其中classes不包含内容，如果缺少，则通过supplement");
        ChatCompletionRequest request = getNewRequest(projectInfo.toString());
        handleContent(request,valueToJson(chat(query.toString(), request)));
    }

    public String readFile(File file) {
        try {
            return FileRW.readTextFile(file).getContent();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public void handleContent(ChatCompletionRequest request, JSONObject jsonObject) {
        String type = jsonObject.getString("type");
        switch (type) {
            case "need": {
                StringBuilder stringBuilder = new StringBuilder();
                JSONArray files;
                try {
                    files = jsonObject.getJSONArray("files");
                } catch (JSONException e) {
                    String query = "";
                    handleContent(request, handleThrowable(request, query, e));
                }

            }
            case "code": {

            }
            case "supplement": {

            }
            case "think": {

            }
        }
    }

    LockAtomicLong lockAtomicLong = new LockAtomicLong(new CodeLock());

    public JSONObject handleThrowable(ChatCompletionRequest request, String content, Throwable throwable) {
        if(lockAtomicLong.get() >2){
            System.out.println("连续错误次数过多，已停止 \n"+ content+" "+throwable);
            return new JSONObject();
        }
        JSONObject req = getRequestJson("error", String.format("对于内容：\n%s\n当前发生以下问题\n%s", content, FileRW.getStackTrace(throwable)));
        lockAtomicLong.add(1);
        JSONObject jsonObject = valueToJson(chat(req.toString(), request));
        lockAtomicLong.set(0);
        return jsonObject;
    }

    public JSONObject valueToJson(String text) {
        int start = text.indexOf("{");
        int end = text.lastIndexOf("}") + 1;
        String substring = text.substring(start, end);
        try {
            return new JSONObject(substring);
        } catch (JSONException e) {
            return handleThrowable(getNewRequest(), String.format("原文:\n%s\n裁剪后内容:\n%s\n裁剪代码为：\n%s\n请调整输出格式，使其满足要求", text, substring, "text.substring(text.indexOf(\"{\"), text.lastIndexOf(\"}\")+1)"), e);
        }
    }
    private JSONObject getRequestJson(String type,String message) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("type", type);
        jsonObject.put("message", message);
        return jsonObject;
    }
    public static ChatCompletionRequest getNewRequest(String... prompts){
        ChatCompletionRequest request = new ChatCompletionRequest();
        StringBuilder systemPrompt =new StringBuilder("你是一个全能的ai助理，你需要根据用户的问题解决问题\n" +
                "在思考中，尽可能避免幻觉，当需要实际的代码内容时补充上下文时，通过need类型回复\n" +
                "如果需要生成一个类的md文档，需要根据这个类的实际来生成\n" +
                "问题格式在提问格式中选择其一，回复格式在回答格式中选择其一，且在回答中不要做过多的描述，所有回复内容在指定格式中包含,严格的json格式\n" +
                "格式参考如下\n"+CueWord.Format+"\n" +
                "最终回答格式参考\n" +
                "{" +
                "{\n" +
                "      \"type\": \"实际字段\",\n" +
                "       实际所需内容字段   "+
                "    }" +
                "}\n");
        for (String prompt : prompts) {
            systemPrompt.append(prompt).append("\n");
        }
        request.addMessage(new Message(Message.Role.SYSTEM, systemPrompt.toString()));
        System.out.println(request);
        return request;
    }

}
